﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;

namespace ICSharpCode.AvalonEdit
{
    public partial class TextEditorExt
    {
        private Point _myMousePlacementPoint;

        private void MouseDown(object sender, MouseButtonEventArgs e)
        {
            var scrollViewer = (ScrollViewer) sender;
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _myMousePlacementPoint = scrollViewer.PointToScreen(Mouse.GetPosition(scrollViewer));
            }
        }

        private void MouseMove(object sender, MouseEventArgs e)
        {
            var scrollViewer = (ScrollViewer) sender;

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var currentPoint = scrollViewer.PointToScreen(Mouse.GetPosition(scrollViewer));

                if (currentPoint.Y < _myMousePlacementPoint.Y)
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - 3);
                }
                else if (currentPoint.Y > _myMousePlacementPoint.Y)
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + 3);
                }

                if (currentPoint.X < _myMousePlacementPoint.X)
                {
                    scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - 3);
                }
                else if (currentPoint.X > _myMousePlacementPoint.X)
                {
                    scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + 3);
                }
            }

            _myMousePlacementPoint = scrollViewer.PointToScreen(Mouse.GetPosition(scrollViewer));
        }

        private void PART_ScrollViewer_OnScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            
        }

        private Timer _timer;

        private double rest;

        private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (Keyboard.GetKeyStates(Key.LeftCtrl) == KeyStates.Down)
                return;

            var scrollViewer = (ScrollViewer) sender;
            if(_timer==null)
                {
                    _timer = new Timer() {Interval = 1};
                    _timer.Tick += (o, args) =>
                        {
                            if(rest==0) _timer.Stop();
                            scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - rest/10);
                            rest = rest/1.1;
                            if (rest*rest < 5) rest = 0;
                        };
                    
                }

            rest = e.Delta * e.Delta * e.Delta/10000.0;
            e.Handled = true;
            _timer.Start();
        }
    }
}
